package com.isdepci.common.utils.sql;

import com.isdepci.common.utils.DateUtils;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 数据库备份
 */
public class MysqlUtil {

	/**
	 * 备份数据库文件
	 */
	public static void backup(String mysqlPath,String mysqlBackup,
							  String address,String databaseName,
							  String username,String password) {
		System.out.println("数据库开始备份,请稍侯......");
		String outFileName = databaseName+"-"+ DateUtils.dateTimeNow() +".sql";
		File backupath = new File(mysqlBackup);
		if (!backupath.exists()) {
			backupath.mkdir();
		}
		StringBuilder sb = new StringBuilder();
		sb.append(mysqlPath).append("mysqldump ").append("--opt ").append("-h ");
		sb.append(address).append(" --user=").append(username);
		sb.append(" --password=").append(password);
		sb.append(" --lock-all-tables=true --result-file=").append(mysqlBackup);
		sb.append(outFileName).append(" --default-character-set=utf8 ");
		sb.append(databaseName);
		Runtime cmd = Runtime.getRuntime();
		try {
			Process p = cmd.exec(sb.toString());
			try {
				p.waitFor();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("数据库开始备份完成！文件："+outFileName);
	}

	/**
	 *  获取备份的所有数据库文件
	 */
	public static List<Map<String,Object>> selectSqlFiles(String mysqlBackup){
		List<Map<String,Object>> list =new ArrayList<>();
		File file = new File(mysqlBackup);
		File[] array = file.listFiles();
		if(array==null||array.length<=0){
			return list;
		}
		int num = 0;
		for (File value : array) {
			if (value.isFile()) {
				num=num+1;
				Map<String,Object> map = new HashMap<>();
				System.out.println(value.getName());
				map.put("fileName",value.getName());
				map.put("fileUrl",value.getPath());
				map.put("fileTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(value.lastModified()));
				list.add(map);
			}
		}
		return list;
	}

	/**
	 * 删除指定的数据库文件
	 */
	public static void deleteBackupSqlFile(String mysqlBackup,String fileName){
		File file = new File(mysqlBackup+fileName);
		if (file.isFile()) {
			file.delete();
			System.out.println("删除成功！文件："+fileName);
			return;
		}
		System.out.println("删除失败！文件："+fileName);
	}
}
